package com.ddzh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddzh.dto.UserDto;
import com.ddzh.entity.PageReq;
import com.ddzh.entity.PageRes;
import com.ddzh.mapper.CheckItemMapper;
import com.ddzh.mapper.UserMapper;
import com.ddzh.pojo.*;
import com.ddzh.service.*;
import com.ddzh.vo.UserVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RoleService roleService;

    @Transactional
    @Override
    public boolean saveOrUpdateUser(UserDto userDto) {
        //用户账户唯一
        //判断当前是添加还是修改
        if(userDto.getUser().getId()==null){// 添加
            //判断数据库中是否有相同账户名的用户
            if (this.baseMapper.findByUsername(userDto.getUser().getUserName()) !=null ){
                return false;
            }
        }
        //保存用户数据
        this.saveOrUpdate(userDto.getUser());
        //维护中间表数据
        //先清理掉之前维护的关系
        userRoleService.deleteByUserId(userDto.getUser().getId());
        //重新插入数据
        List<UserRole> list = new ArrayList<>();
        if (userDto.getRoleIds()!=null) {
            for (Long roleId : userDto.getRoleIds()) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userDto.getUser().getId());
                userRole.setRoleId(roleId);
                list.add(userRole);
            }
            userRoleService.saveBatch(list);
        }

        return true;
    }

    @Override
    public PageRes<User> findByPage(PageReq pageReq) {
        //分页查询时将用户角色信息一并查出来

        IPage<User> iPage = new Page<>();
        iPage.setSize(pageReq.getPageSize());
        iPage.setCurrent(pageReq.getCurrentPage());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete",0);
        if (pageReq.getQueryString() !=null && "".equals(pageReq.getQueryString().trim())==false) {
            queryWrapper.like("username", pageReq.getQueryString());
        }
        queryWrapper.orderByDesc("id");
        IPage<User> page = this.page(iPage, queryWrapper);
        PageRes<User> pageRes = new PageRes<>();
        pageRes.setList(page.getRecords());
        pageRes.setTotal(page.getTotal());
        return pageRes;
    }

    @Override
    public boolean deleteById(Long id) {
        //删除之前要判断当前用户是否正在被角色使用
        List<Role> roleList = roleService.findByUserId(id);
        if (roleList.size()>0){//用户正在被角色使用
            return false;
        }
        User user = new User();
        user.setId(id);
        user.setIs_delete(1);

        return this.updateById(user);
    }

    @Override
    public List<User> getDetail(Long groupId) {
        return null;
    }

    @Override
    public List<UserVo> findAll(PageReq pageReq) {
        /*
        select rt.role_name
            from user_role_t urt left join role_t rt on urt.role_id=rt.id
            where urt.user_id=2
         */
        ArrayList<UserVo> userVoList = new ArrayList<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete" ,0);

        if (pageReq.getQueryString()!=null && "".equals(pageReq.getQueryString())==false){
            queryWrapper.and(wapper->{
                wapper.like("username",pageReq.getQueryString()).or()
                        .like("real_name",pageReq.getQueryString());
            });
        }
        queryWrapper.orderByDesc("id");

        List<User> list = list(queryWrapper);
        for (User user : list) {
            //查询每一个用户的角色名=>直接返回集合
            List<String> roleNameList = roleService.findRoleNameByUserId(user.getId());

            //将 用户 和 角色名 存在集合中
            UserVo userVo = new UserVo();
            userVo.setIs_delete(user.getIs_delete());
            userVo.setRoleNameList(roleNameList);
            userVo.setPassword(user.getPassword());
            userVo.setUserName(user.getUserName());
            userVo.setRealName(user.getRealName());
            userVo.setId(user.getId());
            userVoList.add(userVo);
        }

        return userVoList;
    }

    @Override
    public boolean modifyPassword(Long userId, String password) {
        //根据用户id查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",userId);
        queryWrapper.eq("is_delete",0);
        User user = this.getOne(queryWrapper);
        if (user==null){//用户不存在
            return false;
        }
        user.setPassword(password);
        return this.updateById(user);
    }

    @Override
    public List<String> findUserNameByURoleId(Long roleId) {

        return this.baseMapper.findUserNameByURoleId(roleId);
    }
}
